package org.flowers.unbeaten.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.flowers.unbeaten.generator.Generator;
import org.flowers.unbeaten.generator.configuration.DatabaseConfiguration;
import org.flowers.unbeaten.generator.constant.GeneratorConstant;
import org.flowers.unbeaten.generator.entity.ExpandTemplateEntity;
import org.flowers.unbeaten.generator.entity.GeneratorEntity;
import org.flowers.unbeaten.generator.pagination.LayPage;
import org.flowers.unbeaten.service.IGeneratorService;
import org.flowers.unbeaten.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 代码生成 前端控制器
 * </p>
 *
 * @author RyanWang
 * @since 2021-08-13
 */
@Api(tags = "代码生成-代码生成管理")
@RestController
@RequestMapping("/generator/generator")
public class GeneratorController {

    @Autowired
    private IGeneratorService generatorService;

    @Autowired
    private DatabaseConfiguration databaseConfiguration;

    @PostMapping("/list")
    @ApiOperation(value = "分页获取数据库列表接口")
    public LayPage list(String tableName, String tableDescribe) {
        return generatorService.getTables(tableName, tableDescribe);
    }

    @PostMapping("/getFields")
    @ApiOperation(value = "通过表名获取数据库表字段")
    public LayPage getFields(String tableName) {
        return generatorService.getFields(tableName);
    }

    @PostMapping("/execute")
    @ApiOperation(value = "执行代码生成")
    public void execute(HttpServletResponse response, @RequestBody GeneratorEntity generatorEntity) throws Exception {
        // 设置数据源
        generatorEntity.setDataSource(databaseConfiguration);
        // 追加模板
        List<ExpandTemplateEntity> templatesList = new ArrayList<>();
        if (generatorEntity.getCreatePage()) {
            templatesList.add(new ExpandTemplateEntity("html", "/templates/ftl/page-list.html", "-list", GeneratorConstant.DOT_HTML));
            templatesList.add(new ExpandTemplateEntity("html", "/templates/ftl/page-add.html", "-add", GeneratorConstant.DOT_HTML));
            templatesList.add(new ExpandTemplateEntity("html", "/templates/ftl/page-edit.html", "-edit", GeneratorConstant.DOT_HTML));
        }
        generatorEntity.setExtendTemplate(templatesList);
        // 构建生成器
        Generator generator = Generator.builder(generatorEntity);
        String path = generator.execute();
        // 下载并删除临时文件
        FileUtils.downloadFile(path + "code.zip", "code.zip", true, response);
        FileUtils.deleteFile(path);
    }
}
